import React, { Component } from 'react'

import Header from '../../core/components/header';
import Dialog from '../../core/utils/dialog';
import { Get, getHost, Post, UpdateFile } from '../../core/utils/fetch';
import './index.css';

class RegisterBg extends Component {

    state = {
        imageSrc: 'img/up.png',
    };

    componentDidMount = () => {
        Get(`/spi/registBg/getBg`)
            .then((imageData) => {
                this.setState({ imageSrc: getHost() + `/api/file/${imageData.imgId}` });
            });
    };

    render() {
        return (

            <div>
                <Header title="系统管理" subTitle="System Manage"></Header>

                <div className="row">
                    <div className="col-lg-4">
                        <h2>注册页面背景图</h2>

                        <div className="upload-img">
                            <label>
                                <input id="fileII" type="file" className="true-up-load" onChange={this._changeFile} />
                                <img src={this.state.imageSrc} alt="上传默认图片" className="true-img" />
                            </label>

                        </div>
                        <div className="upload-tips" style={{"color": "red"}}>
                            图片尺寸640*1010像素，图片大小不超过1M
                        </div>
                        <button type="button" className="btn btn-sm btn-primary btn-upload" onClick={this._save}>保存</button>
                    </div>
                </div>
            </div>
        )
    }

    _changeFile = () => {
        var file = window.jQuery('#fileII')[0].files[0]; //获取file对象
        if (!/image\/\w+/.test(file.type)) {
            return false;
        }
        var reader = new window.FileReader(); //声明一个FileReader实例
        reader.readAsDataURL(file); //调用readAsDataURL方法来读取选中的图像文件
        reader.onload = (e) => {
            this.setState({ imageSrc: reader.result });
        };
    };

    _save = () => {
        UpdateFile(window.jQuery('#fileII')[0], (imgId) => {
            Post(`/spi/registBg/saveBg?imageId=${imgId}`)
                .then(() => {
                    Dialog.alert('修改成功', function () {
                        this.setState({ imageSrc: getHost() + `/api/file/${imgId}` });
                    });
                });
        });
    };
}

export default RegisterBg